package com.qltv.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.qltv.pojo.Token;

/**
 * 
 * 类名：TokenUtil
 * 描述：Token操作类
 * @author telnet
 * 创建时间：2018年1月12日
 */
public class TokenUtil {
	private static final Logger logger = Logger.getLogger(TokenUtil.class);
	
	/**
	 * 从数据库中获取token
	 * @return map
	 */
	public static Map<String,Object> getToken(){
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		StringBuffer sql = new StringBuffer();
		sql.append("select * from t_token order by createTime desc limit 0,1");
		String access_token="";
		Map<String,Object> map = new HashMap<String, Object>();
		Integer expires_in = 0;
		try {
			conn = DBUtility.getConnection();
			pstat = conn.prepareStatement(sql.toString());
			rs = pstat.executeQuery();
			if(rs.next()){
				access_token = rs.getString("access_token");
				expires_in = rs.getInt("expires_in");
				map.put("access_token", access_token);
				map.put("expires_in", expires_in);
			}
		} catch (Exception e) {
			logger.error("数据库连接异常："+e.getMessage());
		}finally{
			DBUtility.dispose(conn);
		}
		return map;
	}
	
	
	public static void saveToken(Token token){
		Connection conn = null;
		PreparedStatement pstat = null;
		
		try {
			conn = DBUtility.getConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("insert into t_token(access_token,expires_in,createTime) values ");
			sql.append("(?,?,?)");
			pstat = conn.prepareStatement(sql.toString());
			pstat.setString(1, token.getAccessToken());
			pstat.setInt(2, token.getExpiresIn());
			long now = new Date().getTime();
			pstat.setTimestamp(3, new java.sql.Timestamp(now));
			pstat.execute();
			//System.out.println(sql.toString());
		} catch (Exception e) {
			logger.error("数据库异常："+e.getMessage());
		}finally{
			DBUtility.dispose(conn);
		}
	}
	

}
